package hb;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import zhuzhuwang.HibernateSessionFactory;

public class RentOrderDao {
	private SessionFactory sessions=null;
	private Session mySession=null;
	private Transaction tx;

	public RentOrderDao(){
		sessions=new Configuration().configure().buildSessionFactory();
	}
	
	public void insert(House house,String userName){	
		mySession=sessions.openSession();	
		tx=mySession.beginTransaction();
		
		RentOrder rentOrder=new RentOrder();
		
		rentOrder.setDate(new java.util.Date());
		rentOrder.setHouse(house);
		rentOrder.setUser((new UserDao()).getUser(userName));
		
		try{
			mySession.save(rentOrder);
			tx.commit();
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			mySession.close();
		}
	}
	
	public List getAll(){
		List list=null;
		
		mySession=sessions.openSession();		
		String hql="from RentOrder u";
		Query query=mySession.createQuery(hql);
		
		list=query.list();
		mySession.close();
		
		return list;
	}
	
	public RentOrder getRentOrder(String orderID){
		RentOrder rentOrder=new RentOrder();
		
		mySession=sessions.openSession();
		String hql="from RentOrder u where u.orderId=:uid";
		
		Query query=mySession.createQuery(hql);
		
		query.setParameter("uid", Integer.parseInt(orderID));
		
		List list=query.list();
		Iterator it=list.iterator();
		if(it.hasNext())
		{
			rentOrder=(RentOrder) it.next();
		}
		mySession.close();
		
		return rentOrder;
	}
	
	public void update(RentOrder rentOrder){
		mySession=sessions.openSession();
		tx=mySession.beginTransaction();
		mySession.update(rentOrder);
		tx.commit();
		mySession.close();
	}
	
	public void delete(RentOrder rentOrder){
		mySession=sessions.openSession();
		tx=mySession.beginTransaction();
		mySession.delete(rentOrder);
		tx.commit();
		mySession.close();
	}
	
	public List getMyRentOrder(String owner){
		List list=null;
		
		UserDao userDao=new UserDao();
		
		mySession=sessions.openSession();		
		
		String hql="from RentOrder u where u.user=:uid";
		
		Query query=mySession.createQuery(hql);
		
		User userI=userDao.getUser(owner);
		
		query.setParameter("uid", userI);
		
		list=query.list();
		
		mySession.close();
		
		return list;
	}
}
